/**
 * Cookie 持久化测试 - 使用生产环境 puppeteerManager
 * 通过实际调用 getLiveInfo 来验证 Cookie 复用
 */

// 需要先启动 TypeScript server 编译环境
const { execSync } = require('child_process');
const path = require('path');

async function testProductionCookie() {
  console.log('🧪 测试生产环境 Cookie 持久化...\n');

  try {
    // 动态导入编译后的 puppeteer-service
    const { puppeteerManager } = require('./dist/puppeteer-service');

    console.log('✅ 加载 puppeteerManager 成功\n');

    // 等待初始化完成
    await puppeteerManager.initialize();
    console.log('✅ Puppeteer 初始化完成\n');

    // 使用一个真实的主播ID进行测试
    // 这里使用抖音号测试 (可以换成任何真实的主播)
    const testInputs = [
      'MS4wLjABAAAA1234567890',  // 假设的 sec_uid，会失败但会发送请求
      '1234567890',               // 假设的房间ID
      '9876543210'                // 另一个假设的房间ID
    ];

    const results = [];

    for (let i = 0; i < testInputs.length; i++) {
      const input = testInputs[i];
      console.log(`📍 测试 ${i + 1}: 调用 getLiveInfo('${input}')`);

      try {
        const startTime = Date.now();
        const info = await puppeteerManager.getLiveInfo(input);
        const duration = Date.now() - startTime;

        results.push({
          test: i + 1,
          input: input,
          success: true,
          duration: duration,
          roomId: info.roomId,
          nickname: info.nickname,
          status: info.status
        });

        console.log(`✅ 成功 - 房间ID: ${info.roomId}, 主播: ${info.nickname}, 状态: ${info.status}`);
        console.log(`   耗时: ${duration}ms\n`);
      } catch (err) {
        const duration = Date.now() - startTime;
        results.push({
          test: i + 1,
          input: input,
          success: false,
          duration: duration,
          error: err.message
        });

        console.log(`❌ 失败 - ${err.message}`);
        console.log(`   耗时: ${duration}ms\n`);
      }

      // 等待一下再发送下一个请求
      if (i < testInputs.length - 1) {
        await new Promise(resolve => setTimeout(resolve, 1000));
      }
    }

    // 分析结果
    console.log('📊 测试结果分析:\n');

    const successfulTests = results.filter(r => r.success);
    const failedTests = results.filter(r => !r.success);

    console.log(`✅ 成功: ${successfulTests.length} 个`);
    console.log(`❌ 失败: ${failedTests.length} 个\n`);

    if (successfulTests.length > 0) {
      const avgDuration = successfulTests.reduce((sum, r) => sum + r.duration, 0) / successfulTests.length;
      console.log(`⏱️  平均耗时: ${avgDuration.toFixed(0)}ms\n`);

      console.log('💡 Cookie 持久化验证:');
      console.log('   如果所有请求都成功且耗时相近，说明 Cookie 被正确复用');
      console.log('   如果第一次请求耗时明显较长，可能是在获取新 Cookie');
      console.log('   后续请求耗时较短，说明复用了已有的 Cookie\n');

      // 检查耗时趋势
      if (successfulTests.length > 1) {
        const firstDuration = successfulTests[0].duration;
        const subsequentDurations = successfulTests.slice(1).map(r => r.duration);
        const avgSubsequent = subsequentDurations.reduce((a, b) => a + b, 0) / subsequentDurations.length;

        if (firstDuration > avgSubsequent * 1.5) {
          console.log('✅ 第一次请求耗时较长，后续请求较快 → Cookie 复用生效！');
        } else {
          console.log('ℹ️  所有请求耗时相近 → Cookie 从第一次就开始复用');
        }
      }
    } else {
      console.log('⚠️  所有测试都失败了，无法验证 Cookie 持久化');
      console.log('💡 建议: 使用真实存在的主播ID或房间号进行测试\n');
    }

    console.log('🧪 测试完成');

  } catch (err) {
    console.error('❌ 测试失败:', err);
    console.log('\n💡 提示: 请确保已编译 TypeScript 代码:');
    console.log('   cd server && npm run build\n');
  }
}

// 运行测试
testProductionCookie().catch(console.error);
